/*
 * To change this license header, choose License Headers in Project Properties.
 * To change this template file, choose Tools | Templates
 * and open the template in the editor.
 */
package org.alvin.ocpp.ui;

import com.google.common.base.Strings;
import eu.chargetime.ocpp.NotConnectedException;
import eu.chargetime.ocpp.OccurenceConstraintException;
import eu.chargetime.ocpp.UnsupportedFeatureException;
import lombok.Data;
import org.alvin.mini_inject.annotations.MiniComponent;
import org.alvin.mini_inject.annotations.MiniInject;
import org.alvin.mini_inject.annotations.MiniRun;
import org.alvin.ocpp.server.OCPP1_6JSONServer;
import org.alvin.ocpp.utils.OcppUtils;

import javax.swing.*;
import java.beans.PropertyChangeEvent;
import java.beans.PropertyChangeListener;
import java.util.UUID;
import java.util.stream.Collectors;

/**
 * @author 86139
 */
@Data
@MiniComponent
public class OcppSimuatorFrame extends javax.swing.JFrame {
    @MiniInject
    private OCPP1_6JSONServer ocpp16JSONServer;

    private boolean started = false;

    /**
     * Creates new form OcppSimuatorFrame
     */
    public OcppSimuatorFrame() {
        initComponents();
        setLocationRelativeTo(null);
        txtIp.setText(OcppUtils.getRealIP());
        txtPort.setText("8889");
        DefaultComboBoxModel comboBoxModel = new DefaultComboBoxModel<>();
        jcbCommand.setModel(comboBoxModel);

        jcbClient.setModel(new DefaultComboBoxModel<>());
    }

    @MiniRun
    public void initUI() throws Exception {
        javax.swing.UIManager.setLookAndFeel(javax.swing.UIManager.getSystemLookAndFeelClassName());
        /* Create and display the form */
        java.awt.EventQueue.invokeLater(new Runnable() {
            public void run() {
                setVisible(true);
            }
        });
        DefaultComboBoxModel comboBoxModel = (DefaultComboBoxModel) this.jcbCommand.getModel();
        for (String cmd : this.ocpp16JSONServer.getCmds().stream().sorted().collect(Collectors.toList())) {
            comboBoxModel.addElement(cmd);
        }
        jcbCommand.setModel(comboBoxModel);
    }

    /**
     * This method is called from within the constructor to initialize the form.
     * WARNING: Do NOT modify this code. The content of this method is always
     * regenerated by the Form Editor.
     */
    @SuppressWarnings("unchecked")
    // <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents
    private void initComponents() {

        jTabbedPane1 = new javax.swing.JTabbedPane();
        jPanel1 = new javax.swing.JPanel();
        jLabel1 = new javax.swing.JLabel();
        txtIp = new javax.swing.JTextField();
        jLabel2 = new javax.swing.JLabel();
        txtPort = new javax.swing.JTextField();
        jButton1 = new javax.swing.JButton();
        jButton2 = new javax.swing.JButton();
        jTabbedPane2 = new javax.swing.JTabbedPane();
        jScrollPane1 = new javax.swing.JScrollPane();
        txtConsole = new javax.swing.JTextArea();
        jLabel3 = new javax.swing.JLabel();
        jcbClient = new javax.swing.JComboBox<>();
        jLabel4 = new javax.swing.JLabel();
        jcbCommand = new javax.swing.JComboBox<>();
        btnSend = new javax.swing.JButton();

        setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE);
        setTitle("Ocpp模拟器-V-0.01-超哥哥专用");

        jLabel1.setText("服务器IP:");

        jLabel2.setText("端口：");

        jButton1.setText("启动");
        jButton1.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                jButton1ActionPerformed(evt);
            }
        });

        jButton2.setText("停止");
        jButton2.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                jButton2ActionPerformed(evt);
            }
        });

        txtConsole.setColumns(20);
        txtConsole.setRows(5);
        jScrollPane1.setViewportView(txtConsole);

        jTabbedPane2.addTab("控制台", jScrollPane1);

        jLabel3.setText("客户端:");

        jLabel4.setText("命令：");

        btnSend.setText("发送命令");
        btnSend.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                btnSendActionPerformed(evt);
            }
        });

        javax.swing.GroupLayout jPanel1Layout = new javax.swing.GroupLayout(jPanel1);
        jPanel1.setLayout(jPanel1Layout);
        jPanel1Layout.setHorizontalGroup(
                jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                        .addGroup(jPanel1Layout.createSequentialGroup()
                                .addContainerGap()
                                .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                                        .addComponent(jTabbedPane2)
                                        .addGroup(jPanel1Layout.createSequentialGroup()
                                                .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                                                        .addComponent(jLabel1)
                                                        .addComponent(jLabel3))
                                                .addGap(18, 18, 18)
                                                .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING, false)
                                                        .addGroup(jPanel1Layout.createSequentialGroup()
                                                                .addComponent(txtIp, javax.swing.GroupLayout.PREFERRED_SIZE, 304, javax.swing.GroupLayout.PREFERRED_SIZE)
                                                                .addGap(37, 37, 37)
                                                                .addComponent(jLabel2))
                                                        .addGroup(jPanel1Layout.createSequentialGroup()
                                                                .addComponent(jcbClient, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                                                                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                                                                .addComponent(jLabel4)))
                                                .addGap(18, 18, 18)
                                                .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING, false)
                                                        .addComponent(txtPort, javax.swing.GroupLayout.DEFAULT_SIZE, 270, Short.MAX_VALUE)
                                                        .addComponent(jcbCommand, 0, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
                                                .addGap(34, 34, 34)
                                                .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING, false)
                                                        .addGroup(jPanel1Layout.createSequentialGroup()
                                                                .addComponent(jButton1)
                                                                .addGap(18, 18, 18)
                                                                .addComponent(jButton2))
                                                        .addComponent(btnSend, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
                                                .addGap(0, 104, Short.MAX_VALUE)))
                                .addContainerGap())
        );

        jPanel1Layout.linkSize(javax.swing.SwingConstants.HORIZONTAL, new java.awt.Component[]{jLabel1, jLabel3});

        jPanel1Layout.linkSize(javax.swing.SwingConstants.HORIZONTAL, new java.awt.Component[]{jcbClient, txtIp});

        jPanel1Layout.setVerticalGroup(
                jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                        .addGroup(jPanel1Layout.createSequentialGroup()
                                .addContainerGap()
                                .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                                        .addComponent(jLabel1)
                                        .addComponent(txtIp, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                                        .addComponent(jLabel2)
                                        .addComponent(txtPort, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                                        .addComponent(jButton1)
                                        .addComponent(jButton2))
                                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
                                .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.CENTER)
                                        .addComponent(jLabel3)
                                        .addComponent(jcbClient, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                                        .addComponent(jLabel4)
                                        .addComponent(jcbCommand, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                                        .addComponent(btnSend))
                                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, 28, Short.MAX_VALUE)
                                .addComponent(jTabbedPane2, javax.swing.GroupLayout.PREFERRED_SIZE, 505, javax.swing.GroupLayout.PREFERRED_SIZE)
                                .addContainerGap())
        );

        jPanel1Layout.linkSize(javax.swing.SwingConstants.VERTICAL, new java.awt.Component[]{jLabel1, jLabel3});

        jPanel1Layout.linkSize(javax.swing.SwingConstants.VERTICAL, new java.awt.Component[]{jcbClient, txtIp});

        jTabbedPane1.addTab("Ocpp-1.6-JSONServer", jPanel1);

        getContentPane().add(jTabbedPane1, java.awt.BorderLayout.CENTER);

        pack();
    }// </editor-fold>//GEN-END:initComponents

    private void jButton1ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jButton1ActionPerformed
        // TODO add your handling code here:
        //启动
        if (Strings.isNullOrEmpty(txtIp.getText().trim())) {
            JOptionPane.showMessageDialog(null, "请输入IP");
            return;
        }
        if (Strings.isNullOrEmpty(txtPort.getText().trim())) {
            JOptionPane.showMessageDialog(null, "请输入端口");
            return;
        }
//        jButton1.setEnabled(false);
//        started = true;
        if (!ocpp16JSONServer.hasListeners("log")) {
            ocpp16JSONServer.addPropertyChangeListener("log", new PropertyChangeListener() {
                @Override
                public void propertyChange(PropertyChangeEvent evt) {
                    Object[] logData = (Object[]) evt.getNewValue();
                    for (Object log : logData) {
                        txtConsole.append(log.toString());
                        txtConsole.append("\t");
                    }
                    txtConsole.append("\n");
                }
            });
        }

        ocpp16JSONServer.addPropertyChangeListener("online", new PropertyChangeListener() {
            @Override
            public void propertyChange(PropertyChangeEvent evt) {
                DefaultComboBoxModel model = (DefaultComboBoxModel) jcbClient.getModel();
                UUID uuid = (UUID) evt.getNewValue();
                model.addElement(uuid.toString());
                jcbClient.setModel(model);
            }
        });

        ocpp16JSONServer.addPropertyChangeListener("offline", new PropertyChangeListener() {
            @Override
            public void propertyChange(PropertyChangeEvent evt) {
                DefaultComboBoxModel model = (DefaultComboBoxModel) jcbClient.getModel();
                UUID uuid = (UUID) evt.getNewValue();
                model.removeElement(uuid.toString());
                jcbClient.setModel(model);
            }
        });

        try {
            ocpp16JSONServer.start(txtIp.getText().trim(), Integer.parseInt(txtPort.getText().trim()));
            txtConsole.setText("服务启动完成\n");
        } catch (Exception e) {
            txtConsole.setText("启动失败\n");
        }
    }//GEN-LAST:event_jButton1ActionPerformed

    private void jButton2ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jButton2ActionPerformed
        // TODO add your handling code here:
        //停止
        ocpp16JSONServer.stop();
        txtConsole.setText("服务停止\n\n");
//        jButton1.setEnabled(true);
//        started = false;
    }//GEN-LAST:event_jButton2ActionPerformed

    private void btnSendActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btnSendActionPerformed
        // TODO add your handling code here:
        System.out.println("发送命令");
        if (jcbClient.getSelectedItem() == null) {
            JOptionPane.showMessageDialog(null, "选择客户端", "提示", JOptionPane.WARNING_MESSAGE);
            return;
        }
        if (jcbCommand.getSelectedItem() == null) {
            JOptionPane.showMessageDialog(null, "选择命令", "提示", JOptionPane.WARNING_MESSAGE);
            return;
        }
        String uuid = jcbClient.getSelectedItem().toString();
        String cmd = jcbCommand.getSelectedItem().toString();
        try {
            ocpp16JSONServer.sendCmd(uuid, cmd);
        } catch (Exception e) {
            e.printStackTrace();
            JOptionPane.showMessageDialog(null, "发送出错，" + e.getMessage(), "提示", JOptionPane.WARNING_MESSAGE);
        }
    }//GEN-LAST:event_btnSendActionPerformed


    // Variables declaration - do not modify//GEN-BEGIN:variables
    private javax.swing.JButton btnSend;
    private javax.swing.JButton jButton1;
    private javax.swing.JButton jButton2;
    private javax.swing.JLabel jLabel1;
    private javax.swing.JLabel jLabel2;
    private javax.swing.JLabel jLabel3;
    private javax.swing.JLabel jLabel4;
    private javax.swing.JPanel jPanel1;
    private javax.swing.JScrollPane jScrollPane1;
    private javax.swing.JTabbedPane jTabbedPane1;
    private javax.swing.JTabbedPane jTabbedPane2;
    private javax.swing.JComboBox<String> jcbClient;
    private javax.swing.JComboBox<String> jcbCommand;
    private javax.swing.JTextArea txtConsole;
    private javax.swing.JTextField txtIp;
    private javax.swing.JTextField txtPort;
    // End of variables declaration//GEN-END:variables
}
